<?php

namespace app\common\controller;

use think\Controller;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Log;
use think\facade\Request;

class Common extends Controller
{
    protected $config = null;

    protected function initialize()
    {
        parent::initialize();
        $this->config = get_site_config();

        $runtime_path = Env::get('runtime_path');
        if ( delete_dir_file(	$runtime_path . 'temp/') ) {
//            echo "del";
        }
    }

    /**
     * 获取模板
     * @param string $template 模板名称
     * @param array $vars 模板参数
     * @param array $config
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $config = [])
    {
        $domain = str_replace(array('https://','http://'),'',Request::domain());
        $domain = explode('.',$domain);
        if (is_array($domain)) {
            if ($domain[0] == 'm') {
                $template .= '_m';
            }elseif ($domain[0] == 'mip') {
                $template .= '_mip';
            }
        }

        return parent::fetch($template, $vars, $config);
    }


    /**
     * 生成静态
     * @param string $htmlFile 文件名称
     * @param string $htmlPath 文件路径
     * @param string $templateFile 模板文件
     * @return bool
     */
    protected function buildHtml($htmlFile='',$htmlPath='',$templateFile='') {
        $content    =   $this->fetch($templateFile);
        $htmlPath   =   !empty($htmlPath) ? $htmlPath : Env::get('root_path') . '/public/'; // 项目目录下的html目录
        $htmlFile   =   $htmlPath.$htmlFile.'.html';
        $dir   =  dirname($htmlFile);
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        if(file_put_contents($htmlFile,$content) === false) {
            return false;
        } else {
            return true;
        }
    }


    /**
     * 输出json 数据
     * @param array $data
     * @param int $code
     * @param string $msg
     */
    protected function echoJson($data = array(),$code = 200,$msg = 'ok')
    {
        $data = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        );
        header('Content-Type: application/json; charset=utf-8');
        exit(json_encode($data));
    }
}
